from pydub import AudioSegment
from pydub.playback import play
from datetime import datetime
import pathlib

def read_audio_part():
    cur_path=pathlib.Path(__file__).parent
    audio_fold=cur_path/'audio'

    fen_wav=AudioSegment.from_wav(audio_fold/'fen.wav')
    dian_wav=AudioSegment.from_wav(audio_fold/'dian.wav')
    now_is_wav=AudioSegment.from_wav(audio_fold/'xianzaishi.wav')
    ban_wav=AudioSegment.from_wav(audio_fold/'ban.wav')
    zheng_wav=AudioSegment.from_wav(audio_fold/'zheng.wav')
    
    audio_parts= {
        'dian':dian_wav,
        'fen':fen_wav,
        'nowis':now_is_wav,
        'ban':ban_wav,
        'zheng':zheng_wav
    }
    for i in range(11):
        audio_parts[str(i)]=AudioSegment.from_wav(audio_fold/f'{i}.wav')
    return audio_parts

audio_parts=read_audio_part()

def build_number_audio(n):
    if n<10:
        return audio_parts[str(n)]
    elif n==10:
        return audio_parts[str(10)]
    else:
        ten=n//10
        one=n%10        
        result= audio_parts[str(ten)]+audio_parts[str(10)] if ten>1 else audio_parts[str(10)]
        if one!=0:
            result += audio_parts[str(one)]
        return result

def build_alarm_audio(h=None,m=None):
    now=datetime.now()
    hour=h if h is not None else now.hour
    min=m if m is not None else now.minute
    full_audio=audio_parts['nowis']+build_number_audio(hour)+audio_parts['dian']
    if min==0:
        full_audio+=audio_parts['zheng']
    elif min==30:
        full_audio+=audio_parts['ban']
    else:
        full_audio+=build_number_audio(min)+audio_parts['fen']
    return full_audio

def alarm(h=None,m=None):
    audio=build_alarm_audio(h,m)
    # print(audio.duration_seconds)
    play(audio)

# def can_alarm():
#     slience_hour=[11,0,1,2,3,4,5,6]

def main():
    import schedule, time
    schedule.every().hour.at('00:00').do(alarm)
    schedule.every().hour.at('30:00').do(alarm)
    

    while True:
        n= schedule.idle_seconds()
        if n is None:
            print('No more jobs, exit.')
            break
        elif n<-60:
            print(f'Previous is expired over 60 seconds, passed.')
            continue
        elif n>0:
            print(f'Next alarming is after [{n}] seconds...')
            time.sleep(10)
        schedule.run_pending()


if __name__ == '__main__':
    main()




